package com.dkd.system.utils;

import java.security.SecureRandom;
import java.util.Random;

public class RandomKeyGenerator {
    
    // 定义可用的字符集（数字+大小写字母）
    private static final String CHAR_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final Random RANDOM = new SecureRandom();
    
    /**
     * 生成指定长度的随机密钥
     * @param length 密钥长度
     * @return 随机生成的密钥字符串
     */
    public static String generateRandomKey(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("密钥长度必须大于0");
        }
        
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // 从字符池中随机选择一个字符
            int index = RANDOM.nextInt(CHAR_POOL.length());
            sb.append(CHAR_POOL.charAt(index));
        }
        return sb.toString();
    }
    
    /**
     * 生成默认长度(8)的随机密钥
     * @return 8位随机密钥
     */
    public static String generateRandomKey() {
        return generateRandomKey(8);
    }
    
    // 示例用法
    public static void main(String[] args) {
        System.out.println("16位随机密钥: " + generateRandomKey());
        System.out.println("32位随机密钥: " + generateRandomKey(32));
        System.out.println("8位随机密钥: " + generateRandomKey(8));
    }
}